package com.gonsin.gview.logic.services.data;

import com.gonsin.gview.annotations.GContext;
import com.gonsin.gview.logic.model.DataRequest;
import com.gonsin.i18n.logic.T;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * json语句处理器
 */
public class GJsonDataManager extends GDataManager {

    private GContext context;

    private String dataId;

    private String json;

    private Object result;

    private String titleName;

    public GJsonDataManager(GContext context, String dataId, String json, String titleName) {
        super(GDataPickerManager.class.getName(), json);
        this.context = context;
        this.dataId = dataId;
        this.titleName = titleName;
        this.json = json;
        Gson gson = new GsonBuilder()
                .setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
                .enableComplexMapKeySerialization()
                .disableHtmlEscaping().create();
        Type type = new TypeToken<Object>() {
        }.getType();
        Object map = gson.fromJson(json, type);
        this.result = map;
    }

    @Override
    public Object generalData(HttpServletRequest request, HttpServletResponse response, DataRequest dataRequest) {
        if(result instanceof List){
            // 针对I18N做转换
            if(StringUtils.isEmpty(titleName)){
                return result;
            }
            List<Map<String, Object>> list = (List<Map<String, Object>>) result;
            list = copyList(list);
            for(Map<String, Object> item : list){
                if(item == null){
                    continue;
                }
                if(StringUtils.isEmpty(titleName)){
                    continue;
                }
                Object title = item.get(titleName);
                if(title != null && title instanceof String){
                    title = T.t((String) title);
                    item.put(titleName, title);
                }
            }
            return list;
        }
        return result;
    }

    private List<Map<String, Object>> copyList(List<Map<String, Object>> list) {
        List<Map<String, Object>> listNew = new ArrayList<>();
        for(Map<String, Object> item : list){
            if(item == null){
                continue;
            }
            Map<String, Object> newItem = new HashMap<>(item);
            listNew.add(newItem);
        }
        return listNew;
    }
}
